package com.stlm2.controller;

import com.aliyun.opensearch.CloudsearchSearch;
import com.aliyun.opensearch.CloudsearchSuggest;
import com.stlm2.core.redis.RedisClient;
import com.stlm2.dems.dao.GoodsCategoryDao;
import com.stlm2.dems.entity.GoodsCategory;
import com.stlm2.dems.entity.GoodsCategoryLevel;
import com.stlm2.dems.service.DdmGoodsService;
import com.stlm2.dems.service.GoodsCategoryService;
import com.stlm2.util.DingDangMaoSearch;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


/**
 * Created by zlqon 2017/5/21.
 */
@Controller
@RequestMapping("/openSearchC")
public class openSearchController {

    @Resource
    public DingDangMaoSearch dingDangMaoSearch;
    @Resource
    private GoodsCategoryService goodsCategoryService;
    @Resource
    private GoodsCategoryDao goodsCategoryDao;
    @Resource
    private DdmGoodsService ddmGoodsService;


    /**
     * Author：fuchunyu
     * Date：2017/10/19
     * Description：叮当网商品开放搜索
     */
    @ResponseBody
    @RequestMapping(value="/goodSearch.json",produces="application/json;charset=UTF-8")
    public String  goodSearch(ModelMap model,String companyCode,String keywords,String page,String goodsCategory_id,String isDate,String isSales,String isPrice,String parentCategory_id,String category_id,String unCategory_id){
        String json = "";
        int pageNo = 1;
        JedisPool pool = null;
        Jedis jedis = null;
        if (NumberUtils.isDigits(page) && !"0".equals(page)) {
            pageNo = NumberUtils.toInt(page);
        }
        try {
            pool = RedisClient.getPool();
            jedis = pool.getResource();
            CloudsearchSearch search = dingDangMaoSearch.getSearch();
            //设置开放搜索的应用名称
            String openSearchName="";
            if(NumberUtils.isDigits(companyCode)){
                openSearchName=getopenSearchName(Integer.parseInt(companyCode));
            }else {
                openSearchName="ddm_goods";
            }
            search.addIndex(openSearchName);
            // 指定搜索返回的格式。
            search.setFormat("json");
            search.setStartHit((pageNo - 1) * 20);
            search.setHits(20);
            // 设定过滤条件
            search.addFilter("state>0");
            // 设定排序方式 + 表示正序 - 表示降序
            if(!StringUtils.isEmpty(keywords)) {
                //设置搜索的关键字
                search.setQueryString("ddm:'"+ keywords + "'");

                search.addSort("id", "-");
            }
            if(!StringUtils.isEmpty(unCategory_id)){
                GoodsCategory goodsCategory=goodsCategoryService.findEntityById(Integer.parseInt(unCategory_id));
                if(goodsCategory.getGoodsCategoryLevel().equals(GoodsCategoryLevel.Level1))
                    category_id=goodsCategory.getId().toString();
                if(goodsCategory.getGoodsCategoryLevel().equals(GoodsCategoryLevel.Level2))
                    parentCategory_id=goodsCategory.getId().toString();
                if(goodsCategory.getGoodsCategoryLevel().equals(GoodsCategoryLevel.Level3))
                    goodsCategory_id=goodsCategory.getId().toString();
            }

                if(category_id!=null&&!category_id.equals("0")&&!"".equals(category_id)) {
                    List<GoodsCategory> list=goodsCategoryDao.getByParentCategoryId(Integer.parseInt(category_id));
                    StringBuffer buffer=new StringBuffer();
                    for (GoodsCategory goodsCategory:list){
                        buffer.append("parent_category_id:'"+goodsCategory.getId()+"' OR ");
                    }
                    buffer.append("parent_category_id:''");
                    search.setQueryString(buffer.toString());
                }
                if(goodsCategory_id!=null&&!goodsCategory_id.equals("0")&&!"".equals(goodsCategory_id)) {
                    search.setQueryString("goods_category_id:'"+goodsCategory_id+"'");
                }
                if(parentCategory_id!=null&&!parentCategory_id.equals("0")&&!"".equals(parentCategory_id)) {
                    search.setQueryString("parent_category_id:'"+parentCategory_id+"'");
                }
                if(!StringUtils.isEmpty(isDate)) {
                    if(isDate.equals("0"))
                         search.addSort("create_time", "-");
                    if(isDate.equals("1"))
                        search.addSort("create_time", "+");
                }
                if(!StringUtils.isEmpty(isSales)) {
                    if(isSales.equals("0"))
                        search.addSort("sales_volume", "-");
                    if(isSales.equals("1"))
                        search.addSort("sales_volume", "+");
                }
                if(!StringUtils.isEmpty(isPrice)) {
                    if(isPrice.equals("0"))
                        search.addSort("member_price", "-");
                    if(isPrice.equals("1"))
                        search.addSort("member_price", "+");
                }
                search.addDistinct("goods_id",1,1,"false",null,"true",0);
                search.setPair("duniqfield:goods_id");
                json = search.search();
                if (!json.isEmpty()) {
                    JSONObject jsonObject = new JSONObject(json);
                    String status = jsonObject.getString("status");
                    if (status.equals("OK")) {
                        JSONObject result = jsonObject.getJSONObject("result");
                        model.put("num", result.getInt("num"));
                        model.put("pageNo", page);
                        model.put("recordsTotal", result.getInt("viewtotal"));
                        model.put("totalPage", result.getInt("total") / 20);
                        JSONArray jsonArray = result.getJSONArray("items");
                        if(!StringUtils.isEmpty(keywords)) {
                            if (jsonArray.length()>0) {
                                //用于将搜索的关键字存入redis有序集合中
                                Long redisPopSearch = jedis.zrank("popSearch", keywords);
                                if (redisPopSearch != null) {
                                    jedis.zincrby("popSearch", +1, keywords);
                                } else {
                                    jedis.zadd("popSearch", 1, keywords);
                                }
                            }
                        }

                        model.put("code", "1");
                        model.put("msg", "success");
                       // model.put("datas", jsonArray);
                        model.put("datas",ddmGoodsService.convertJsonArray(jsonArray));
                        return new JSONObject(model).toString();
                    }
                }

        }catch (Exception e) {
            model.put("code", "0");
            model.put("msg","搜索失败");
            return new JSONObject(model).toString();
        }
        finally {
            pool.returnResource(jedis);
        }
        return new JSONObject(model).toString();
    }
    /**
     * 开放搜索，下拉提示
     * keywords:关键字
     */
    @ResponseBody
    @RequestMapping(value="/goodSuggest.json",produces="application/json;charset=UTF-8")
    public String goodSuggest(String  companyCode,ModelMap model,String keywords){
        try {
            String indexName = "";
            if(NumberUtils.isDigits(companyCode)){
                indexName=getopenSearchName(Integer.parseInt(companyCode));
            }else {
                indexName="ddm_goods";
            }
            String suggestName = "goods_xiala";
            CloudsearchSuggest suggest = dingDangMaoSearch.getSuggest(indexName, suggestName);
            suggest.setHit(10);
            suggest.setQuery(keywords);
            String result = suggest.search();

            JSONObject jsonResult = new JSONObject(result);
            List<String> suggestions = new ArrayList<String>();

            if (!jsonResult.has("errors")) {
                JSONArray itemsJsonArray = (JSONArray) jsonResult.get("suggestions");
                for (int i = 0; i < itemsJsonArray.length(); i++){
                    JSONObject item = (JSONObject) itemsJsonArray.get(i);
                    suggestions.add(item.getString("suggestion"));
                }
                model.put("code",1);
                model.put("msg","success");
                model.put("result",suggestions);
                return  new JSONObject(model).toString();
            } else {
                ;
            }
        } catch (UnknownHostException e) {
            ;
        } catch (ClientProtocolException e) {
            ;
        } catch (IOException e) {
            ;
        }
        return null;
    }

    /**
     * 获取热门搜索关键字
     *
     */
    @ResponseBody
    @RequestMapping(value="/popSearch.json",produces="application/json;charset=UTF-8")
    public String popSearch(String  companyCode){
        JedisPool pool = null;
        Jedis jedis = null;
        Set<String> popList =new HashSet();

        try {
            pool = RedisClient.getPool();
            jedis = pool.getResource();

            popList =jedis.zrevrange("popSearch",0,8);
            if(popList.size()<9){
                jedis.zadd("initpopSearch",1,"苹果");
                jedis.zadd("initpopSearch",1,"三星");
                jedis.zadd("initpopSearch",1,"华为");
                jedis.zadd("initpopSearch",1,"诺基亚");
                jedis.zadd("initpopSearch",1,"摩托罗拉");
                jedis.zadd("initpopSearch",1,"富士");
                jedis.zadd("initpopSearch",1,"尼康");
                jedis.zadd("initpopSearch",1,"佳能");
                jedis.zadd("initpopSearch",1,"索尼");
                popList =jedis.zrevrange("initpopSearch",0,8);
            }

        }catch (Exception e){
            e.printStackTrace();
            return CodeContent.getModelByCode(0,"获取数据失败",popList);
        }
        finally {
            pool.returnResource(jedis);
        }
        return CodeContent.getModelByCode(1,"success",popList);

    }


    private  String getopenSearchName(int companyCode){
        switch (companyCode){
            case 1:
                return "ddm_goods";
            case 2:
                return "ddm_goods_yongcheng";
            case 3:
                return "ddm_goods_xtd";
            default:
                return null;

        }
    }
}
